package org.itboys.ace.web.lasted;

import org.apache.commons.lang3.StringUtils;
import org.itboys.admin.common.SystemLoginUserPermission;
import org.itboys.admin.constant.AdminCookieConstant;
import org.itboys.admin.entity.lasted.SystemMenu;
import org.itboys.admin.entity.lasted.SystemRolePermission;
import org.itboys.admin.entity.lasted.SystemUser;
import org.itboys.admin.entity.lasted.SystemUserRole;
import org.itboys.admin.service.lasted.SystemMenuService;
import org.itboys.admin.service.lasted.SystemRolePermissionService;
import org.itboys.admin.service.lasted.SystemUserRoleService;
import org.itboys.admin.service.lasted.SystemUserService;
import org.itboys.admin.tools.*;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.commons.utils.cookie.CookieUtils;
import org.itboys.commons.utils.encryption.Digests;
import org.itboys.commons.utils.servlet.ServletContextHolder;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.interceptor.AdminIntercepter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class AceSystemLoginController extends BaseController{


	@Autowired
	private SystemUserService userService;
	@Autowired
	private SystemRolePermissionService rolePermissionService;
	@Autowired
	private SystemUserRoleService userRoleService;
	@Autowired
	private ResourceHolder resourceHolder;
	@Autowired
	private SystemMenuService menuService;

	/**
	 * 进入登入页面
	 * @param model
	 * @param request
	 */
	@RequestMapping("/admin/login")
	public ModelAndView login(Model model,HttpServletRequest request){
		//登入过的用户名一般放在cookieli里
		model.addAttribute("username", AdminCookieHolder.getAdminUserName());
		model.addAttribute("isPassword", AdminCookieHolder.getAdminPassword());
		/*model.addAttribute("staticRoot",resourceHolder.getStringValue("staticRoot"));
		model.addAttribute("adminRoot",resourceHolder.getStringValue("adminRoot"));
		model.addAttribute("imgRoot",resourceHolder.getStringValue("imgRoot"));*/
		return new ModelAndView("login");
	}


	/**
	 * 异步登入地址
	 * @param request
	 * @param response
	 * @param userName
	 * @param password
	 * @param yzm
	 */
	@RequestMapping("/admin/doLogin")
	public void doLogin(
					HttpServletRequest request,
					HttpServletResponse response,
					@RequestParam(value="userName",required = true)String userName,
					@RequestParam(value="password",required = true)String password,
					@RequestParam(value="yzm",required = true)String yzm){

		SystemUser loginUser = userService.findOne(userName);
		if(loginUser==null){
			AjaxUtils.renderText(response, "0");//用户不存在

		}
		if(!StringUtils.equals(loginUser.getPassword(), Digests.md5(password))){
			AjaxUtils.renderText(response, "-1");//密码不正确

		}
		//判断用户是否失效
		if(loginUser.getIsDeleted()==1||loginUser.getStatus()!=0){

			AjaxUtils.renderText(response, "-4");//用户被冻结
		}
		//获取session的验证码
		String _yzm = (String) request.getSession().getAttribute("rand");
		if(!StringUtils.equals(_yzm, yzm)){
			AjaxUtils.renderText(response, "-2");//验证码不正确

		}
		//把用户名 弄到cookie里。保证自动登陆，回填登陆名称和
		CookieUtils.addCookieWithBase64(response, WebConstants.CookieKey.COOKIE_KEY_ADMIN_USER_NAME, loginUser.getUserName(), 864000);

		AdminCookieHolder.setAdminUserName(loginUser.getUserName());
		//	回填登陆名密码
		/*if("true".equals(request.getParameter("autoLogin"))){
			AdminCookieHolder.setAdminPassword(user.getPassword());
		}*/
		AdminSessionHolder.setAdminUserId(loginUser.getId());

		//-------------------缓存登陆用户的接口权限-----------
		//判断是否开启权限校验
		logger.info("用户功能权限缓存开始A");
		if(AdminIntercepter.is_open_operate_permission_check){
			//超级用户不需要权限
			logger.info("用户功能权限缓存开始B");
			if(loginUser.getIsSuper()!=1) {
				logger.info("用户功能权限缓存开始C");
				Map<String, Object> param = new HashMap<String, Object>();
				//获取用户的角色
				param.put("userId", loginUser.getId());
				param.put("isDeleted", 0);
				List<SystemUserRole> userRoles = userRoleService.list(param);
				List<Long> roleIds = new ArrayList<>();
				for (SystemUserRole userRole : userRoles) {
					roleIds.add(userRole.getRoleId());
				}
				if (ListUtil.isNotNull(roleIds)) {
					logger.info("用户功能权限缓存开始D");
					param.clear();
					param.put("roleId in", roleIds);
					param.put("type", SystemRolePermission.system_role_permission_type_operate);

					List<SystemRolePermission> rolePermissions = rolePermissionService.list(param);
					//获取功能的菜单
					List<Long> menuIds = new ArrayList<Long>();
					for(SystemRolePermission rolePermission:rolePermissions){
						menuIds.add(rolePermission.getMenuId());
					}
						if(ListUtil.isNotNull(menuIds)){
							logger.info("用户功能权限缓存开始E");
							param.clear();
							param.put("isDeleted",0);
							param.put("id in",menuIds);
							param.put("isMenu",0);
							List<SystemMenu> operates = menuService.list(param);
							//组织成字符串的形式，把接口地址缓存起来
							List<SystemLoginUserPermission> loginUserPermissions = new ArrayList<SystemLoginUserPermission>();
							for(SystemMenu operate:operates){
								SystemLoginUserPermission per =
										new SystemLoginUserPermission(
												loginUser.getId(),operate.getRootUrl()+operate.getOperateUrl());

								loginUserPermissions.add(per);
							}
							logger.info("用户功能权限缓存完成，合计接口权限+:"+loginUserPermissions.size());
							SystemLoginUserPermission.loginUserOperatePermssion=loginUserPermissions;

						}

				}

			}
		}

		//设置登录最大时间
		ServletContextHolder.getSession().setMaxInactiveInterval(Integer.valueOf(resourceHolder.getStringValue("sessionMaxInactiveInterval")));
		//登陆验证成功
		AjaxUtils.renderText(response, "1");//登入成功。js控制转跳



		//Integer resultCode =loginService.doLogin(response,userName,password,yzm,(String) request.getSession().getAttribute("rand"));

		//AjaxUtils.renderText(response, resultCode.toString());


	}

	/**
	 * 异步退出
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/admin/logout")
	public ModelAndView logout(HttpServletRequest request,HttpServletResponse response,Model model){
		request.getSession().setAttribute(AdminCookieConstant.COOKIE_USER_NAME, null);
		CookieUtils.removeCookie(response, AdminCookieConstant.COOKIE_PASSWORD);
		AdminSessionHolder.removeAdminUserId();
		model.addAttribute("staticRoot",resourceHolder.getStringValue("staticRoot"));
		model.addAttribute("adminRoot",resourceHolder.getStringValue("adminRoot"));
		model.addAttribute("imgRoot",resourceHolder.getStringValue("imgRoot"));
		return new ModelAndView("redirect:/admin/login");
	}
}
